package com.yzy.baselibrary.http.ssl;

import android.annotation.SuppressLint;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

/**
 * description: SSLManager.
 *
 * @date 2018/6/16 14:43.
 * @author: YinZeYu.
 */
public class SSLManager {
  /**
   * 创建SSLSocket的工厂类
   *
   * @return 返回一个SSLSocket的工厂类
   */
  public static SSLSocketFactory createSSLSocketFactory() {
    SSLSocketFactory ssfFactory = null;
    try {
      SSLContext sc = SSLContext.getInstance("SSL");
      sc.init(null, new TrustManager[] { new TrustAllCerts() }, new SecureRandom());
      ssfFactory = sc.getSocketFactory();
    } catch (Exception e) {
      e.printStackTrace();
    }
    return ssfFactory;
  }

  /**
   * description: X509证书信任管理器类
   *
   * @author YinZeYu
   * @date 2018/6/8 16:11
   */
  private static class TrustAllCerts implements X509TrustManager {
    @SuppressLint("TrustAllX509TrustManager")
    @Override
    public void checkClientTrusted(X509Certificate[] chain, String authType) {
    }

    @SuppressLint("TrustAllX509TrustManager")
    @Override
    public void checkServerTrusted(X509Certificate[] chain, String authType) {
    }

    @Override
    public X509Certificate[] getAcceptedIssuers() {
      return new X509Certificate[0];
    }
  }
}
